package com.mingqijia.gassafety.authority.security.facade;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mingqijia.gassafety.authority.api.req.privilege.CreatePrivilegeReqDTO;
import com.mingqijia.gassafety.authority.api.req.privilege.QueryPrivilegeReqDTO;
import com.mingqijia.gassafety.authority.api.req.privilege.UpdatePrivilegeReqDTO;
import com.mingqijia.gassafety.authority.api.resp.privilege.PrivilegeRespDTO;
import com.mingqijia.gassafety.authority.api.web.facade.PrivilegeManageFacade;
import com.mingqijia.gassafety.authority.dal.command.RemovePrivilegeCommand;
import com.mingqijia.gassafety.authority.dal.handler.PrivilegeTranslator;
import com.mingqijia.gassafety.authority.dal.provider.PrivilegeProvider;
import com.mingqijia.gassafety.db.entity.auth.PrivilegeEntry;
import com.mingqijia.gassafety.shared.facade.BaseFacade;
import com.mingqijia.gassafety.shared.handler.GlobalAuthenticationException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * REST接口
 * @author Damon S.
 * @version v0.2
 * @date 2021-06-19
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class PrivilegeManageFacadeImpl extends BaseFacade implements PrivilegeManageFacade {

    private final PrivilegeProvider provider;
    private final PrivilegeTranslator translator;


    @Override
    public List<PrivilegeRespDTO> findPrivilege(QueryPrivilegeReqDTO req) {
        Page<PrivilegeEntry> results = provider.find(translator.toCommand(req));
        if (ObjectUtils.isEmpty(results)) {
            throw new GlobalAuthenticationException("操作失败");
        }
        return translator.toRespDTO(results.getRecords());
    }

    @Override
    public String createPrivilege(CreatePrivilegeReqDTO req) {
        return provider.create(translator.toCommand(req));
    }

    @Override
    public void updatePrivilege(UpdatePrivilegeReqDTO req) {
        if (!provider.update(translator.toCommand(req))) {
            throw new GlobalAuthenticationException("创建权限失败");
        }
    }

    @Override
    public void removePrivilege(String privId) {
        RemovePrivilegeCommand command = RemovePrivilegeCommand.builder().privId(privId).build();
        if (!provider.remove(command)) {
            throw new GlobalAuthenticationException("删除失败");
        }
    }
}
